<?php

namespace plugin\muadmin\app\admin\controller\auth;

use plugin\muadmin\app\common\base\BaseAdminController;
use plugin\muadmin\app\common\model\AuthGroup;
use plugin\muadmin\app\common\model\AuthGroupAccess;
use think\facade\Db;

class Admin extends BaseAdminController
{
    public function initialize()
    {
        parent::initialize();
        $this->model = (new \plugin\muadmin\app\common\model\Admin());

        $groupList = AuthGroup::where('status',1)->select()->toArray();
        $groupList = list_to_tree($groupList,'id','pid','children');
        $this->assignConfig('groupList',$groupList);
    }
    public function index()
    {
        if($this->request->isAjax()){
            $this->indexGetData = true;
            $res = parent::index();
            foreach ($res['rows'] as &$row){
                $row->group_names = $row->authgroup();
            }
            unset($row);
            return $this->success('ok',$res);
        }
        return parent::index();
    }
    public function edit()
    {
        $ids = $this->param('ids');
        if(empty($ids)){
            return $this->error('请选择编辑项');
        }
        $row = $this->model->where($this->model->getPk(), $ids)
            ->withoutField('password,salt')
            ->find();
        if(empty($row)){
            return $this->error('数据不存在');
        }
        if($this->request->isAjax()){
            $data = $this->param('row');
            if(empty($data)){
                return $this->error('请选择编辑项row');
            }
            if(empty($data['group_ids'])){
                return $this->error('请选择用户组');
            }
            if(!empty($data['password'])){
                $data['password'] = create_password($data['password'],$row->salt);
            }
            $groupIds = $data['group_ids'];
            unset($data['group_ids']);
            $res = $row->save($data);
            if(!$res){
                return $this->error('保存失败');
            }
            foreach ($groupIds as $groupId){
                $has = AuthGroupAccess::where('uid',$ids)->where('group_id',$groupId)->find();
                if(empty($has)){
                    AuthGroupAccess::create([
                        'uid'=>$ids,
                        'group_id'=>$groupId
                    ]);
                }
            }
            $accessIds = AuthGroupAccess::where('uid',$ids)->whereNotIn('group_id',$groupIds)->column('id');
            if(!empty($accessIds)){
                AuthGroupAccess::destroy($accessIds);
            }
            return $this->success("保存成功");
        }
        $row->group_ids = AuthGroupAccess::where('uid',$ids)->column('group_id');
//        print_r($row->toArray());
        $this->assignConfig('row',$row);
        return $this->fetch();
    }
    public function add()
    {
        if($this->request->isAjax()){
            $data = $this->param('row');
            $has = $this->model->where('username',$data['username'])->find();
            if(!empty($has)){
                return $this->error('用户已存在');
            }
            if(empty($data['group_ids'])){
                return $this->error('请选择用户组');
            }
            $groupIds = $data['group_ids'];
            unset($data['group_ids']);
            if(empty($data['avatar'])){
                $data['avatar'] = '/app/muadmin/image/avatar.png';
            }
            if(empty($data['password'])){
                return $this->error('请填写密码');
            }
            $salt = random_str(6);
            $data['salt'] = $salt;
            $data['password'] = create_password($data['password'],$salt);
            Db::startTrans();
            try {
                $row = $this->model->create($data);
                foreach ($groupIds as $groupId){
                    AuthGroupAccess::create([
                        'uid'=>$row->id,
                        'group_id'=>$groupId
                    ]);
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->error($e->getMessage());
            }
            return $this->success('保存成功');
        }
        return parent::add();
    }
    public function del()
    {
        $ids = $this->param('ids');
        if(empty($ids)){
            return $this->error('请选择要删除的项');
        }
        Db::startTrans();
        try {
            $this->model->destroy($ids);
            AuthGroupAccess::where('uid','in',$ids)->delete();
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error($e->getMessage());
        }
        return $this->success('删除成功');
    }
}